//获取文章列表
let data = {
  pagenum: 1,
  pagesize: 10,
};

function getList() {
  $.ajax({
    type: "GET",
    url: "/my/article/list",
    data: data,
    success: function (res) {
      showPage(res.total);
      let str = "";
      res.data.forEach((item) => {
        str += `
                <tr>
                    <td>${item.title}</td>
                    <td>${item.cate_name}</td>
                    <td>${item.pub_date}</td>
                    <td>${item.state}</td>
                    <td>
                    <button type="button" class="layui-btn layui-btn-xs" data-id='${item.id}'>编辑</button>
                    <button type="button" class="layui-btn layui-btn-xs layui-btn-danger" id='delat' data-id='${item.id}'>删除</button>
                    </td>
               </tr>
                `;
      });
      $(".layui-table tbody").html(str);
    },
  });
}
getList();

//删除文章接口
$("body").on("click", "#delat", function () {
  let id = $(this).data("id");
  layer.confirm("确认删除么？", { icon: 3, title: "提示" }, function (index) {
    $.ajax({
      type: "GET",
      url: `/my/article/delete/` + id,
      success: function (res) {
        getList();
        layer.msg(res.message);
      },
    });
    layer.close(index);
  });
});

// 分页
function showPage(a) {
  let laypage = layui.laypage;
  let options = {
    elem: "page", //注意，这里的是ID，不用加 # 号
    count: a, //数据总数，从服务端得到
    limit: data.pagesize,
    limits: [10, 15, 20, 25], //每页条数的选择项。
    curr: data.pagenum,
    layout:['limit','prev','page','next','count','skip'],
    jump: function(obj, first){
      //obj包含了当前分页的所有参数，比如：
      // console.log(obj.curr); //得到当前页，以便向服务端请求对应页的数据。
      // console.log(obj.limit); //得到每页显示的条数
      //首次不执行
      if(!first){
        data.pagenum = obj.curr
        data.pagesize = obj.limit
        getList()
      }
    }
  };
  laypage.render(options);
}

//获取分类
let form = layui.form;
$.ajax({
  type: "GET",
  url: "/my/category/list",
  success: function (res) {
    let str = "";
    res.data.forEach((item) => {
      str += `<option value="${item.id}">${item.name}</option>`;
    });
    $("#select").append(str);
    form.render("select");
  },
});

//查询
$('#lookup').on('submit',function(e){
  e.preventDefault()
  let cate_id = $('#select').val()
  let state = $('#select2').val()
  console.log(cate_id,state);
  if(cate_id){
    data.cate_id = cate_id
  }else{
    delete data.cate_id
  }
  if(state){
    data.state = state
  }else{
    delete data.state
  }
  data.pagenum =1
  getList()
})


//编辑功能
$('body').on('click','button:contains("编辑")',function(){
  let id = $(this).data('id')
  location.href=`./addArticle.html?id=${id}&num=1`
})